package com.qingyun.web.controller.pcapi.shop;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.constant.UserConstants;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.domain.entity.SysRole;
import com.qingyun.common.core.domain.entity.SysUser;
import com.qingyun.common.core.domain.model.TiktokShopVo;
import com.qingyun.common.core.domain.model.TiktokUser;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.core.validate.AddGroup;
import com.qingyun.common.core.validate.EditGroup;
import com.qingyun.common.utils.StringUtils;
import com.qingyun.common.utils.poi.ExcelUtil;
import com.qingyun.security.controller.BaseController;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokShopInfo;
import com.qingyun.shop.domain.TiktokUserShop;
import com.qingyun.shop.domain.bo.shop.*;
import com.qingyun.shop.domain.vo.TiktokShopStaffPushVo;
import com.qingyun.shop.domain.vo.TiktokShopUserListVo;
import com.qingyun.shop.mapper.TiktokUserShopMapper;
import com.qingyun.shop.service.ITiktokShopInfoService;
import com.qingyun.shop.service.ITiktokShopService;
import com.qingyun.shop.service.ITiktokShopStaffPushService;
import com.qingyun.system.service.ISysRoleService;
import com.qingyun.system.service.ISysUserService;
import com.qingyun.tiktok.basis.response.video.VideoPoiRes;
import com.qingyun.tiktok.config.DyConfig;
import com.qingyun.tiktok.util.TikTokUserByCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@Api(tags = {"^商户管理"})
@AllArgsConstructor
@RestController
@RequestMapping("/system/shop/manager")
public class 	TiktokShopManagerController extends BaseController {

	private final ISysUserService userService;

	private final ITiktokShopService iTiktokShopService;

	private final TiktokUserShopMapper tiktokUserShopMapper;

	private final ITiktokShopInfoService tiktokShopInfoService;

	private final TikTokUserByCodeUtil tikTokUserByCodeUtil;

	private final ISysRoleService roleService;

	private ITiktokShopStaffPushService shopStaffPushService;

	private final DyConfig dyConfig;

	/**
	 * 导出商家列表
	 */
	@ApiOperation("导出商户列表 system:shop:manager:export")
	@PreAuthorize("@ss.hasPermi('system:shop:manager:export')")
	@GetMapping("/export")
	public void export(@Validated TiktokShopQueryBo bo, HttpServletResponse response) {
		List<TiktokShopVo> list = iTiktokShopService.queryList(bo);
		ExcelUtil.exportExcel(list, "商户", TiktokShopVo.class, response);
	}

	/**
	 * 查询商家列表
	 */
	@ApiOperation("^拥有的商户列表 system:shop:manager:list")
	@PreAuthorize("@ss.hasPermi('system:shop:manager:list')")
	@GetMapping("/list")
	public TableDataInfo<TiktokShopVo> list(@Validated TiktokShopQueryBo bo) {
		return iTiktokShopService.queryPageList(bo);
	}
	/**
	 * 查询所有商家列表
	 */
	@ApiOperation("^拥有的商户列表 system:shop:manager:list")
	@PreAuthorize("@ss.hasPermi('system:shop:manager:list')")
	@GetMapping("/listAll")
	public AjaxResult<List<TiktokShopVo>> listAll(@Validated TiktokShopQueryBo bo) {
		return AjaxResult.success(iTiktokShopService.queryList(bo));
	}

	@ApiOperation("^查询商户下管理者账号列表")
	@PreAuthorize("@ss.hasPermi('system:shop:manager:userlist')")
	@GetMapping("/getUserList")
	public TableDataInfo<TiktokShopUserListVo> getUserList(TiktokShopUserListBo queryBo) {
		return iTiktokShopService.queryUserListByShopId(queryBo);
	}

	/**
	 * 新增商户
	 */
	@ApiOperation("^新增商户 system:shop:manager:add")
	@PreAuthorize("@ss.hasPermi('system:shop:manager:add')")
	@RepeatSubmit()
	@PostMapping("/insert")
	public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody TiktokShopAddBo bo) {
		return toAjax(iTiktokShopService.insertByBo(bo) ? 1 : 0);
	}


	@ApiOperation("商户详情信息 system:shop:manager:info")
	@PreAuthorize("@ss.hasPermi('system:shop:manager:info')")
	@GetMapping("/detail/{id}")
	public AjaxResult<TiktokShopVo> shopDetail(@PathVariable("id") Long id) {
		return AjaxResult.success(iTiktokShopService.queryById(id));
	}

	/**
	 * 修改商户信息
	 */
	@ApiOperation("^修改商户信息 system:shop:manager:edit")
	@PreAuthorize("@ss.hasPermi('system:shop:manager:edit')")
	@RepeatSubmit()
	@PostMapping("/edit")
	public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody TiktokShopEditBo bo) {
		return toAjax(iTiktokShopService.updateByBo(bo) ? 1 : 0);
	}


	@PreAuthorize("@ss.hasPermi('system:shop:manager:addUser')")
	@ApiOperation("^添加商户用户账号")
	@PostMapping("/addManagerUser")
	public AjaxResult<Void> addManagerUser(@Validated @RequestBody SysUser user) {
		if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
			return AjaxResult.error("配置账号'" + user.getUserName() + "'失败，登录账号已存在");
		}
		if (StringUtils.isNotEmpty(user.getPhonenumber())
			&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			return AjaxResult.error("配置账号'" + user.getUserName() + "'失败，手机号码已存在");
		}
		if (StringUtils.isNotEmpty(user.getEmail())
			&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			return AjaxResult.error("配置账号'" + user.getUserName() + "'失败，邮箱账号已存在");
		}

		if (ObjectUtil.isNull(user.getShopId())) {
			return AjaxResult.error("商户id不能为空");
		}


		SysRole role_key = roleService.lambdaQuery().eq(SysRole::getRoleKey, "shop_role_key").one();
		user.setRoleIds(new Long[]{role_key.getRoleId()});

		user.setUserType(Constants.SHOP_USER);
		user.setCreateBy(getUsername());
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

		return toAjax(iTiktokShopService.configUser(user, user.getShopId()));
	}

	@PreAuthorize("@ss.hasPermi('system:shop:manager:deleteUser')")
	@ApiOperation("删除商家用户 system:shop:manager:deleteUser")
	@DeleteMapping("/deleteShopUser/{ids}")
	public AjaxResult deleteShopUser(@PathVariable("ids") Long[] ids){

		if (ArrayUtil.contains(ids, getUserId()))
		{
			return error("当前用户不能删除");
		}
		int i = userService.deleteUserByIds(ids);
		tiktokUserShopMapper.delete(Wrappers.lambdaQuery(TiktokUserShop.class).in(TiktokUserShop::getUserId,ids));
		return toAjax(i);
	}

	@ApiOperation("员工推广记录列表")
	@GetMapping("pushList")
	public TableDataInfo<TiktokShopStaffPushVo> staffPushList(Integer pageNum, Integer pageSize,Long userId){
		TableDataInfo<TiktokShopStaffPushVo> tiktokShopStaffPushVoTableDataInfo = shopStaffPushService.selectPageList(null,userId);
		return tiktokShopStaffPushVoTableDataInfo;
	}

	@ApiOperation("获取总推广人数和成功核销人数")
	@GetMapping("getPushCount")
	public AjaxResult getStaffPushCount(Long userId){
		Integer totalCount = shopStaffPushService.selectTotalCount(userId);
		Integer checkCount = shopStaffPushService.selectCheckCount(userId);
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("totalCount",totalCount);
		resultMap.put("checkCount",checkCount);
		return AjaxResult.success(resultMap);
	}

	/**
	 * 修改代商家用户
	 */
	@ApiOperation("修改商户用户信息 system:shop:user:edit")
	@PreAuthorize("@ss.hasPermi('system:shop:user:edit')")
	@PutMapping("/updateShopUser")
	public AjaxResult updateShopUserInfo(@Validated @RequestBody SysUser user){
		userService.checkUserAllowed(user);
		if (StringUtils.isNotEmpty(user.getPhonenumber())
			&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
		{
			return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
		}
		else if (StringUtils.isNotEmpty(user.getEmail())
			&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
		{
			return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}
		user.setUpdateBy(getUsername());
		return toAjax(userService.updateById(user));
	}

	/**
	 * 重置密码
	 */

	@ApiOperation("修改商户下面用户密码 system:shop:user:resetPwd")
	@PreAuthorize("@ss.hasPermi('system:shop:user:resetPwd')")
	@PutMapping("/resetPwd")
	public AjaxResult resetPwd(@RequestBody SysUser user)
	{
		userService.checkUserAllowed(user);
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		user.setUpdateBy(getUsername());
		return toAjax(userService.resetPwd(user));
	}

	/**
	 * 根据用户编号获取详细信息
	 */

	@ApiOperation("获取商户下用户详情信息")
	@GetMapping(value = "/getUserInfo")
	public AjaxResult getInfo(@RequestParam(value = "userId") Long userId)
	{
		Map<String, Object> ajax = new HashMap<>();
		if (StringUtils.isNotNull(userId))
		{
			ajax.put("user", userService.selectUserById(userId));
		}
		return AjaxResult.success(ajax);
	}

	@ApiOperation("/抖音授权二维码地址")
	@GetMapping("/getAuthQrCodeUrl")
	public AjaxResult qrCodeUrl(Long shopId) {
		StringBuilder builder = new StringBuilder();
		builder.append("https://open.douyin.com/platform/oauth/connect/?client_key=");
		builder.append(dyConfig.getAppId());
		builder.append("&response_type=code&scope=trial.whitelist,user_info,video.data,fans.check,item.comment&redirect_uri=");
		builder.append(dyConfig.getShopRedirectUri() + "?shopId=" + shopId);
		return AjaxResult.success(builder.toString());
	}
	/**
	 * 商家抖音授权
	 *
	 * @return
	 */
	@ApiOperation("商家抖音授权")
	@GetMapping("/shopAuth")
	public AjaxResult shopAuth(String code, Long shopId) {
		TiktokUser tiktokUser = tikTokUserByCodeUtil.getTiktokUser(code);
		TiktokShopInfo one = tiktokShopInfoService.lambdaQuery().eq(TiktokShopInfo::getShopId, shopId).one();
		if (ObjectUtil.isNull(one)) {
			TiktokShopInfo tiktokShopInfo = new TiktokShopInfo();
			tiktokShopInfo.setOpenId(tiktokUser.getOpenId());
			tiktokShopInfo.setShopId(shopId);
			tiktokShopInfo.setNickname(tiktokUser.getNickName());
			tiktokShopInfoService.save(tiktokShopInfo);
		} else {
			one.setNickname(tiktokUser.getNickName());
			one.setOpenId( tiktokUser.getOpenId());
			tiktokShopInfoService.updateById(one);
		}
		return AjaxResult.success("授权成功");
	}


	@ApiOperation("获取商家抖音信息")
	@GetMapping("/getTiktokShopInfo")
	public AjaxResult selectTiktokShopInfo(Long shopId){
		TiktokShopInfo one = tiktokShopInfoService.lambdaQuery().eq(TiktokShopInfo::getShopId, shopId).one();
		if (ObjectUtil.isNull(one)||StringUtils.isBlank(one.getOpenId())) {
			return AjaxResult.error("请先授权");
		}
		return AjaxResult.success(one);
	}

	/**
	 * 抖音商家抖音信息修改
	 * @return
	 */

	@ApiOperation("商家抖音信息修改")
	@PutMapping("/updateTiktokShopInfo")
	public AjaxResult editShopUserInfo(@Validated(EditGroup.class) @RequestBody TiktokShopInfoEditBo editBo){
		return toAjax(tiktokShopInfoService.updateByBo(editBo) ? 1 : 0);
	}

	@ApiOperation("查询商家poi地址")
	@GetMapping("/searchPoi")
	public AjaxResult searchPOI(@RequestParam String address){
		List<VideoPoiRes.Poi> pois = iTiktokShopService.searchPOI(address);
		return AjaxResult.success(pois);
	}

}
